﻿using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace JEngine.Framework
{
    public class ResourceManager 
    {
        private static Dictionary<string, string> dic = new Dictionary<string, string>();
        private List<string> RegisterName = new List<string>();

        public ResourceManager()
        {
            TxtLoadDic();
        }

        /// 把 资源配置文件中的信息 读取到 字典中   
        private void TxtLoadDic()
        {
            Debug.Log("资源管理器初始化");
            //1 加载 文本资源【资源配置文件】
            TextAsset ta=  Resources.Load<TextAsset>("ResMap");
            if (ta == null)
            {
                Debug.Log("Not Find ResMap");
                return;

            }
            string mapText =ta.text;
           
            string line = null;
            //2 对文本逐行读取 放到字典中
            using (StringReader reader = new StringReader(mapText))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    //3对每一行进行处理：用"="拆分为两段
                    var keyValue = line.Split('=');

                    //4前一段为key,后一段为value
                    dic.Add(keyValue[0], keyValue[1]);
                    
                }
            }
        }

        //通过资源名取得资源路径 CircleAttackSkill  -- > Skill/CircleAttackSkill
        private string GetValue(string key)
        {
            if (dic.ContainsKey(key))
                return dic[key];
            Debug.LogError($"key:{key}未找到");
            return null;
        }

        // 【启动》读资源配置文件》根据资源名找到资源实际位置》动态加载】
        public T Load<T>(string name, bool isRegister = false) where T : Object
        {
            var t = Resources.Load<T>(GetValue(name));
            if (isRegister && !RegisterName.Contains(name))
            {
                RegisterName.Add(name);
               // Mirror.NetworkClient.RegisterPrefab(t as GameObject);
            }

            return t;
        }

        public GameObject Instantiate(string name)
        {
            GameObject pre = Load<GameObject>(name);

            return GameObject.Instantiate(pre);
        }

        public Object Load(string name)
        {
            return Resources.Load(GetValue(name));
        }

        public Sprite LoadSprite(string spriteName)
        {

            Sprite[] atlas = Resources.LoadAll<Sprite>(GetValue(spriteName));

            if (atlas.Length > 1)
            {
                foreach (var sprite in atlas)
                {
                    if (sprite.name == spriteName)
                    {
                        return sprite;
                    }
                }

                Debug.LogError("没有找到名称为" + spriteName + "的图片");
                return null;
            }

            return atlas[0];
        }
    }
}